package com.bbs.interceptor;

import com.bbs.common.Constants;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *身份验证拦截器
 */
@Component
public class MyBBSLoginInterceptor implements HandlerInterceptor {
    /**
     * 拦截器方法
     * @param request
     * @param response
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //判断request的session中是否存储了用户的键
        if (null == request.getSession().getAttribute(Constants.USER_SESSION_KEY)) {
            /*
             * 将请求重定向到登录页面
             *   response.sendRedirect() 方法用于将客户端重定向到指定的URL
             *   request.getContextPath() 返回当前Web应用的上下文路径
             * */
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        } else {
            return true;
        }
    }

}
